<?php

namespace app\middleware;

use app\logic\admin\L_adminRole;
use \ltcms\middleware\Middleware_contract;

class isAdminAuth implements Middleware_contract
{
    /**
     *  处理请求
     */
    public function handle($request, \Closure $next)
    {
        $controller = str_replace("\\", "/", $request->controller()); //控制器    需要转换 斜杠
        $action = $request->action();   //是方法

        //获取当前控制器和方法功能id
        //获取当前角色绑定功能ids
        $uid = session()->get("uid");
        $paramsObj = getParamsObj();

        $prefix = "app/admin/controller/"; //系统自带控制器前缀
        $paramsObj->params = [
            "uid" => $uid,
            "module" =>   str_replace($prefix,"admin/",$controller),   //控制器过滤掉系统自带前缀
            "action" => $action
        ];
        //共用控制器需要单独添加数据
        if ($paramsObj->params["module"] === "admin/Article") {
            $paramsObj->params["other"] = "moduleId=" . $request->param("moduleId");
        }

        if ($paramsObj->params["module"] === "admin/Category") {
            $paramsObj->params["other"] = "dataType=module&dataId=" . $request->param("dataId");
        }

        $ret = L_adminRole::roleAuthentication($paramsObj);
        if ($ret["error_no"] != 0) {
            if ($request->isGet()) {
                $data=array();
                if (env()->get("APP_debug", "") == 1) {
                    $data = array();
                    $data["request"] = $paramsObj->params;
                }
                return view("admin/error/noAuth",$data);
            } else {
                apiResponse(false, $ret["error_msg"], $ret["error_no"]);
            }

            //上面apiResponse包含exit终端脚本代码,下边不会执行
        }

        $response = $next($request);
        return $response;
    }
}


